package com.agrm.good.service.impl;

import com.agrm.api.client.BrandClient;
import com.agrm.api.client.CategoryClient;
import com.agrm.good.mapper.GoodMapper;
import com.agrm.good.service.GoodService;
import com.agrm.model.brand.pojo.Brand;
import com.agrm.model.category.pojo.Category;
import com.agrm.model.common.dtos.PageRequestDto;
import com.agrm.model.common.dtos.PageResponseResult;
import com.agrm.model.common.dtos.ResponseResult;
import com.agrm.model.good.pojo.Good;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

@CacheConfig(cacheNames = "stmall-seckills-good")
@Service
public class GoodServiceImpl extends ServiceImpl<GoodMapper , Good> implements GoodService {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private GoodMapper goodMapper;

    @Autowired
    private BrandClient brandClient;

    @Autowired
    private CategoryClient categoryClient;



    /**
     * 根据id查询商品详情 包含分类和品牌
     * @param id id
     * @return Good
     */
    @Override
    public Good getGoodDetailById(Integer id) {
        Good good = goodMapper.selectById(id);
        if(good == null){
            throw new RuntimeException("商品不存在");
        }
        try {
            // 查询分类
            ResponseResult<Category> categoryRes = categoryClient.getCategoryById(good.getCategoryId());
            good.setCategory(categoryRes.getData());

            // 查询品牌
            ResponseResult<Brand> brandRes = brandClient.findById(good.getBrandId());
            good.setBrand(brandRes.getData());
        } catch (Exception e) {
            throw new RuntimeException("服务异常，请稍后重试");
        }

        return good;
    }

    /**
     * 根据分类ID查询该分类下的所有商品
     * @param categoryId 分类ID
     * @return 商品列表
     */
    @Override
    public List<Good> getGoodsByCategoryId(Integer categoryId) {
        // 使用MyBatis-Plus的LambdaQueryWrapper进行查询
        LambdaQueryWrapper<Good> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Good::getCategoryId, categoryId)
                   .eq(Good::getIsDel, 0) // 只查询未删除的商品
                   .eq(Good::getIsTakeDown, 0); // 只查询未下架的商品

        return goodMapper.selectList(queryWrapper);
    }

    @Override
    public boolean updateQty(Integer goodId, Integer delta) {
        return goodMapper.updateQty(goodId,delta) > 0;
    }

    @Cacheable(key = "#id")
    @Override
    public Good findSeckillById(Integer id) {
        List<Good> goods = self().findAllSeckill();
        return goods.stream().filter(good -> good.getId().equals(id)).findFirst().orElse(null);
    }

    @Cacheable(key = "'all'")
    @Override
    public List<Good> findAllSeckill() {
        List<Good> goods = goodMapper.findAllSeckill();
        goods.forEach(good -> {
            redisTemplate.opsForValue().set("seckill-stock:"+good.getId(),good.getQty(), Duration.ofMinutes(60));
            redisTemplate.opsForValue().set("seckill-end:"+good.getId(),false, Duration.ofMinutes(65));
        });
        return goods;
    }

    /**
     * 分页查询商品
     *
     * @param pageRequestDto
     * @param name
     * @return
     */
    @Override
    public PageResponseResult getGoodBySearch(PageRequestDto pageRequestDto, String name) {
        pageRequestDto.checkParam();
        Page<Good> page = Page.of(pageRequestDto.getPage(), pageRequestDto.getSize());
        LambdaQueryWrapper<Good> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(Good::getName, name)
                .eq(Good::getIsDel, 0) // 只查询未删除的商品
                .eq(Good::getIsTakeDown, 0); // 只查询未下架的商品

        Page<Good> pageData = goodMapper.selectPage(page, queryWrapper);
        PageResponseResult pageResponseResult = new PageResponseResult((int) pageData.getCurrent(), (int) pageData.getSize(), (int) pageData.getTotal());
        pageResponseResult.setData(pageData.getRecords());
        return pageResponseResult;
    }


    /**
     * 获取促销商品
     * @param categoryName
     * @return
     */
    @Override
    public ResponseResult getPromoGood(String categoryName) {
        //TODO 后期修改
        LambdaQueryWrapper<Good> lambdaQuery = new LambdaQueryWrapper<>();
        lambdaQuery.eq(Good::getBrandId , 2);
        List<Good> list = goodMapper.selectList(lambdaQuery);
        return ResponseResult.okResult(list);
    }


    /**
     * 获取热门商品
     * @param categoryName
     * @return
     */
    @Override
    public ResponseResult getHotGood(List<String> categoryName) {
        List<Good> goods = new ArrayList<>();

        for (String name : categoryName) {
            LambdaQueryWrapper<Good> lambdaQuery = new LambdaQueryWrapper<>();
            lambdaQuery.like(Good::getName, name);
            List<Good> list = goodMapper.selectList(lambdaQuery);
            goods.addAll(list);
        }

        return ResponseResult.okResult(goods);
    }


    private GoodService self() {
        return (GoodService) AopContext.currentProxy();
    }
}
